import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class TicketServiceImpl implements TicketService {
    private ScheduleService scheduleService;
    private List<Ticket> tickets = new ArrayList<>();

    public TicketServiceImpl(ScheduleService scheduleService) {
        this.scheduleService = scheduleService;
    }

    @Override
    public Ticket sellTicket(int scheduleId, int row, int col) {
        Schedule s = scheduleService.getById(scheduleId);
        if (s == null) {
            System.out.println("无此排片");
            return null;
        }
        Hall hall = s.getHall();
        if (!hall.isSeatAvailable(row, col)) {
            System.out.println("座位已售出");
            return null;
        }
        hall.occupySeat(row, col);
        Ticket t = new Ticket(s, row, col);
        tickets.add(t);
        Logger.log("售出票：" + t.getTicketId());
        System.out.println("出票成功：" + t);
        return t;
    }

    @Override
    public void refundTicket(String ticketId) {
        for (Ticket t : tickets) {
            if (t.getTicketId().equals(ticketId) && !t.isRefund()) {
                LocalDateTime now = LocalDateTime.now();
                // 可扩展退票时间判断
                t.getSchedule().getHall().releaseSeat(t.getRow(), t.getCol());
                t.refund();
                Logger.log("退票：" + ticketId);
                System.out.println("退票成功");
                return;
            }
        }
        System.out.println("退票失败，未找到有效电影票");
    }

    @Override
    public List<Ticket> listTickets() {
        return tickets;
    }
}